package com.imddy.wakeonlan;

import com.imddy.wakeonlan.cache.AppCacheMap;
import com.imddy.wakeonlan.service.WakeonlanService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Iterator;
import java.util.Set;

@SpringBootApplication
public class Application implements ApplicationRunner {
    private static final Logger log = LoggerFactory.getLogger(Application.class);

    @Autowired
    private WakeonlanService wakeonlanService;


    public static void main(String[] args) {
        log.info("Application start");
        SpringApplication.run(Application.class, args);
        log.info("Application end");

    }



    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("wakeonlan启动run完成...");

        /** 默认参数 */
        String ip = "";
        String mac = "";


        /** 有帮助与否显示帮助 */
        Set<String> argsSet = args.getOptionNames();
        if (argsSet.isEmpty() || argsSet.contains("help")) {
            printHelp();
            System.exit(1);
        }

        /** 参数赋值 */
        if (!argsSet.isEmpty()) {
            for (Iterator iterator = argsSet.iterator(); iterator.hasNext(); ) {
                String arg = (String) iterator.next();
                if (arg.equalsIgnoreCase("ip")) {
                    if (args.getOptionValues("ip").size() > 0) {
                        ip = args.getOptionValues("ip").get(0);
                    } else {
                        System.out.println("ip参数异常！");
                        printHelp();
                        System.exit(1);
                    }
                }
                if (arg.equalsIgnoreCase("mac")) {
                    if (args.getOptionValues("mac").size() > 0) {
                        mac = args.getOptionValues("mac").get(0);
                    } else {
                        System.out.println("mac参数异常！");
                        printHelp();
                        System.exit(1);
                    }
                }

            }
        }

        log.info("ip:" + ip);
        log.info("mac:" + mac);
        mac = mac.replaceAll("-", ":").toString();
        log.info("ip:" + ip);
        log.info("mac:" + mac);
        AppCacheMap.put("ip", ip);
        AppCacheMap.put("mac", mac);

        wakeonlanService.sendMagicPacket(mac, ip);





    }





    public void printHelp() {
        System.out.println("--help    显示帮助");
        System.out.println("--ip=192.168.106.22    录入IP");
        System.out.println("--mac=74:56:3C:88:FA:CE    录入MAC");
    }



}
